export class ProgressBar {
  constructor(canvas) {
    this.canvas = canvas;
    this.context = this.canvas.getContext('2d');
    this.width = this.canvas.width;
    this.height = this.canvas.height;
    this.progress = 0;
    this.targetProgress = 0; // 目标进度
    this.progressBarWidth = this.width * 0.8; 
    this.progressBarHeight = this.height / 35;
    this.progressBarX = (this.width - this.progressBarWidth) / 2;
    this.progressBarY = this.height / 2;
    this.progressBarColor = '#4CAF50'; 
    this.animationFrameId = null;
    this.isAnimating = false;
  }

  draw() {
    // Save the current canvas state
    this.context.save();

    // Draw the background of progress bar
    this.context.fillStyle = '#ccc';
    this.context.fillRect(this.progressBarX, this.progressBarY, this.progressBarWidth, this.progressBarHeight);

    // Draw progress bar
    this.context.fillStyle = this.progressBarColor;
    const progressWidth = this.progress / 100 * this.progressBarWidth;
    this.context.fillRect(this.progressBarX, this.progressBarY, progressWidth, this.progressBarHeight);

    // Restore the canvas state
    this.context.restore();
  }

  animate() {
    if (Math.abs(this.progress - this.targetProgress) > 0.1) {
      // Smoothly update progress towards targetProgress
      this.progress += (this.targetProgress - this.progress) * 0.05; // Adjust speed as needed
      this.draw();
      this.animationFrameId = requestAnimationFrame(() => this.animate());
    } else {
      // Ensure we reach the target progress
      this.progress = this.targetProgress;
      this.draw();
      this.isAnimating = false;
    }
  }

  setProgress(progress) {
    this.targetProgress = Math.min(100, Math.max(0, progress));
    if (!this.isAnimating) {
      this.isAnimating = true;
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
      }
      this.animate();
    }
  }

  destroy() {
    // 清理动画帧
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
    }
    // 清理进度条区域，但不影响其他内容
    this.context.clearRect(this.progressBarX, this.progressBarY, this.progressBarWidth, this.progressBarHeight);
    this.canvas = null;
    this.context = null;
    this.progress = 0;
    this.targetProgress = 0;
    console.log('Progress bar destroyed.');
  }
}
